package cn.iocoder.yudao.module.scrm.service.marketing.category;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
import cn.iocoder.yudao.module.scrm.controller.admin.marketing.vo.category.MarketingCategoryPageReqVO;
import cn.iocoder.yudao.module.scrm.controller.admin.marketing.vo.category.MarketingCategorySaveReqVO;
import cn.iocoder.yudao.module.system.api.permission.PermissionApi;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import java.util.stream.Collectors;

import cn.iocoder.yudao.module.scrm.dal.dataobject.marketing.MarketingCategoryDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.scrm.dal.mysql.marketing.MarketingCategoryMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static cn.iocoder.yudao.module.scrm.enums.ErrorCodeConstants.*;

/**
 * 营销分类 Service 实现类
 *
 * @author admin
 */
@Service
@Validated
public class MarketingCategoryServiceImpl implements MarketingCategoryService {

    @Resource
    private MarketingCategoryMapper marketingCategoryMapper;

    @Resource
    private AdminUserApi adminUserApi;

    @Resource
    private PermissionApi permissionApi;

    @Override
    public String createMarketingCategory(MarketingCategorySaveReqVO createReqVO) {
        // 插入
        MarketingCategoryDO marketingCategory = BeanUtils.toBean(createReqVO, MarketingCategoryDO.class);
        marketingCategoryMapper.insert(marketingCategory);
        // 返回
        return marketingCategory.getId();
    }

    @Override
    public void updateMarketingCategory(MarketingCategorySaveReqVO updateReqVO) {
        // 校验存在
        validateMarketingCategoryExists(updateReqVO.getId());
        // 更新
        MarketingCategoryDO updateObj = BeanUtils.toBean(updateReqVO, MarketingCategoryDO.class);
        marketingCategoryMapper.updateById(updateObj);
    }

    @Override
    public void deleteMarketingCategory(Integer id) {
        // 校验存在
        validateMarketingCategoryExists(id);
        // 删除
        marketingCategoryMapper.deleteById(id);
    }

    private void validateMarketingCategoryExists(Integer id) {
        if (marketingCategoryMapper.selectById(id) == null) {
            throw exception(MARKETING_CATEGORY_NOT_EXISTS);
        }
    }

    @Override
    public MarketingCategoryDO getMarketingCategory(Integer id) {
        return marketingCategoryMapper.selectById(id);
    }

    @Override
    public PageResult<MarketingCategoryDO> getMarketingCategoryPage(MarketingCategoryPageReqVO pageReqVO) {
        //设置当前登陆人的部门id
        pageReqVO.setDeptId(String.valueOf(adminUserApi.getUser(getLoginUserId()).getCheckedData().getDeptId()));
        return marketingCategoryMapper.selectPage(pageReqVO);
    }

    @Override
    public List<Tree<String>> getMarketingCategoryTreePage(MarketingCategoryPageReqVO pageReqVO) {
        //https://blog.csdn.net/qq_45525848/article/details/132135911 快速获取树形结构 huTool  主见和父id必须为字符串
        //设置当前登陆人的部门id
        //TODO 如果要显示目录就注释这一行
        if( !permissionApi.roleIsSuperAdmin(getLoginUserId()).getCheckedData()) {
            //超级管理员不进行设置
            pageReqVO.setDeptId(String.valueOf(adminUserApi.getUser(getLoginUserId()).getCheckedData().getDeptId()));
        }

        //1.获取所有 资料分类
        pageReqVO.setPageSize(-1);
        PageResult<MarketingCategoryDO> dataList =marketingCategoryMapper.selectPage(pageReqVO);

        if (!dataList.getList().isEmpty() && dataList.getTotal()!=0) {
            //2.配置
            TreeNodeConfig config = new TreeNodeConfig();
            config.setIdKey("id");                              //默认id，可以不设置
            config.setParentIdKey("parentId");                  //父id
            config.setNameKey("name");                          //分类名称
            config.setDeep(3);                                  //最大递归深度
            config.setChildrenKey("childCategoryList");         //孩子节点名称
            //config.setWeightKey("sort");                      //排序字段

            //3.转树
            List<Tree<String>> build = TreeUtil.build(dataList.getList(), "0", config, ((object, treeNode) -> {
                treeNode.putExtra("id", object.getId());
                treeNode.putExtra("parentId", object.getParentId());
                treeNode.putExtra("name", object.getName());
                treeNode.putExtra("deptId", object.getDeptId());
                treeNode.putExtra("deptName", object.getDeptName());
                treeNode.putExtra("level", object.getLevel());
                treeNode.putExtra("name", object.getName());
                treeNode.putExtra("marketingType", object.getMarketingType());
                treeNode.putExtra("ifLevel", object.getIfLevel());
                //扩展属性...
            }));
            return build;
        }
        return Collections.emptyList();

    }



    // 查询指定分类id的所有子分类id（包括自身）
    public List<String> getAllSubCategoryIds(String categoryId) {
        List<String> allSubCategoryIds = new ArrayList<>();
        // 添加自身id
        allSubCategoryIds.add(categoryId);
        // 递归查询子分类id
        recursivelyFindSubCategoryIds(categoryId, allSubCategoryIds);
        return allSubCategoryIds;
    }

    @Override
    public List<String> selecAllIdsByType(String marketingType) {
        MarketingCategoryPageReqVO marketingCategoryPageReqVO = new MarketingCategoryPageReqVO();
        marketingCategoryPageReqVO.setPageSize(-1);
        marketingCategoryPageReqVO.setMarketingType(marketingType);
        return marketingCategoryMapper.selectPage(marketingCategoryPageReqVO)
                .getList()
                .stream()
                .map(MarketingCategoryDO::getId)
                .collect(Collectors.toList());
    }

    // 递归查询子分类id
    private void recursivelyFindSubCategoryIds(String parentId, List<String> resultIds) {
        MarketingCategoryPageReqVO marketingCategoryPageReqVO = new MarketingCategoryPageReqVO();
        marketingCategoryPageReqVO.setPageSize(-1);
        List<MarketingCategoryDO> categorieList =marketingCategoryMapper.selectPage(marketingCategoryPageReqVO).getList();
        if (categorieList != null && !categorieList.isEmpty()) {
            for (MarketingCategoryDO category : categorieList) {
                if (category.getParentId() != null && category.getParentId().equals(parentId)) {
                    // 找到当前父分类下的子分类
                    resultIds.add(category.getId());
                    // 递归查询子分类的子分类
                    recursivelyFindSubCategoryIds(category.getId(), resultIds);
                }
            }
        }
    }


}